<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    :maskClosable="false"
    width="40%"
  >
  <!-- :okAuth="'wms:rd:order:rdOrder:edit'" -->
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdOrderRdsList>
        <BasicTable @register="registerRdOrderRdsTable" @row-click="handleRdOrderRdsRowClick" />
        <!-- <a-button class="mt-2" @click="handleRdOrderRdsAdd" v-auth="'wms:rd:order:rdOrder:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <PrintModal @register="registerPrintModal" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsRdOrderRdOrderForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { RdOrder, rdOrderSave, rdOrderForm, printFx } from '/@/api/wms/rd/order/rdOrder';
  import { printSnNumber } from '/@/api/wms/barcode/encode';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  import PrintModal from '/@/components/print/printModal.vue';
  import { useModal } from '/@/components/Modal';
  import { useGo } from '/@/hooks/web/usePage';
  
  const { ctxPath } = useGlobSetting();
  const go = useGo();

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms.rd.order.rdOrder');
  const { showMessage,createSuccessModal } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<RdOrder>({} as RdOrder);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增出库订单') : t('编辑出库订单'),
    value:  t('封箱标签打印'),
  }));

  const inputFormSchemas: FormSchema[] = [
    
    
   
    {
      label: t('收货地址'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 20,
      },
      colProps: { lg: 24, md: 24 },
      required: true,
    },
    {
      label: t('收货单位'),
      field: 'shdw',
      component: 'Input',
      componentProps: {
        maxlength: 20,
      },
      colProps: { lg: 24, md: 24 },
      // required: true,
    },
    {
      label: t('打印内容'),
      field: 'printType',
      component: 'RadioGroup',
      defaultValue: '1',
      componentProps: {
        dictType: 'rd_order_print_data',
        maxlength: 50,
      },
      colProps: { lg: 12, md: 24 },
      required: true,
    },
    {
      label: t('打印类型'),
      field: 'barSizeType',
      component: 'RadioGroup',
      defaultValue: '100',
      componentProps: {
        dictType: 'bar_size_type7',
        maxlength: 50,
      },
      colProps: { lg: 12, md: 24 },
      required: true,
    },
    {
      label: t('包装件数'),
      field: 'iqty',
      component: 'InputNumber',
      componentProps: {
        maxlength: 20,
      },
      colProps: { lg: 12, md: 24 },
      // required: true,
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t(''),
      field: 'rdOrderRdsList1',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdOrderRdsList',
    },
  ];

  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerRdOrderRdsTable, rdOrderRdsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleRdOrderRdsDelete.bind(this, record),
    //       },
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  async function setRdOrderRdsTableData(_res: Recordable) {
    rdOrderRdsTable.setColumns([
      {
        title: t('商品名称'),
        dataIndex: 'fitemname',
        width: 160,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 16,
        //   disabled:true
        // },
        // editRule: true,
      },
      {
        title: t('邮发代码'),
        dataIndex: 'basInv.yfdh',
        width: 100,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 16,
        //   disabled:true
        // },
        // editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'fqty',
        width: 90,
        align: 'center',
        editRow: true,
        editable: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
    ]);
    rdOrderRdsTable.setTableData(record.value.rdOrderRdsList || []);
  }

  function handleRdOrderRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRdOrderRdsAdd() {
    rdOrderRdsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleRdOrderRdsDelete(record: Recordable) {
    rdOrderRdsTable.deleteTableDataRecord(record);
  }

  async function getRdOrderRdsList() {
    let rdOrderRdsListValid = true;
    let rdOrderRdsList: Recordable[] = [];
    for (const record of rdOrderRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rdOrderRdsListValid = false;
      }
      rdOrderRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rdOrderRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rdOrderRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!rdOrderRdsListValid) {
      throw { errorFields: [{ name: ['rdOrderRdsList'] }] };
    }
    return rdOrderRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rdOrderForm(data);
    record.value = (res.rdOrder || {}) as RdOrder;
    record.value.__t = new Date().getTime();
    record.value.address = record.value.faddress
    setFieldsValue(record.value);
    setRdOrderRdsTableData(res);
    rdOrderRdsTable.clearSelectedRowKeys()
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    let jsonData = [];
    if (!rdOrderRdsTable.getSelectRows().length) {
      jsonData = await getRdOrderRdsList();
    }else{
      jsonData = rdOrderRdsTable.getSelectRows().map(item => {
        return {
          ...item,
          fqty: item.editValueRefs.fqty.value ? item.editValueRefs.fqty.value : 0,
        }
      })
    }

    try {
      const data = await validate();
      data.barType = '7';
      data.id = record.value.djno;
      data.size = data.barSizeType;
      data.companyCode = record.value.companyCode;
      let jsonData = await getRdOrderRdsList();
      data.rdrecords32List = jsonData
      console.log('data', data)
      setDrawerProps({ confirmLoading: true });
      data.fperson = record.value.fperson;
      data.fphone = record.value.fphone;

      const res = await printFx(data);
      if (res.result == "true") {
        closeDrawer();
        go('/wms/rd/order/rdOrder/prinfxEdit?printId=' + res.data.printId);
      } else {
        showMessage(res.message);
      }
      // const res = await printSnNumber(data);
      // if(res.result == "true"){
      //   // setTimeout(closeDrawer);
      //   // createSuccessModal({ 
      //   //   content: '打印 ' + res.fileName,
      //   //   okText: '下载',
      //   //   onOk() {
      //   //     downloadByUrl({ url: ctxPath + res.pdfUrl });
      //   //     closeDrawer();
      //   //   },
      //   // });
      //   let params = {
      //     ids: res.ids,
      //     title: '封箱标签打印',
      //     height: '0.9',
      //     width: '0.7',
      //     fileName: '标签打印fx_100',
      //     uuid:res.uuid
      //   };
      //   openPrintModal(true, params);
      //   // closeDrawer();
      // } else {
      //   showMessage(res.message);
      // } 
      // setDrawerProps({ confirmLoading: true });
      // const params: any = {
      //   isNewRecord: record.value.isNewRecord,
      //   djno: record.value.djno,
      // };
      // data.rdOrderRdsList = await getRdOrderRdsList();
      // // console.log('submit', params, data, record);
      // const res = await rdOrderSave(params, data);
      // showMessage(res.message);
      // setTimeout(closeDrawer);
      // emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }

</style>
